import os
import sys
import shutil
from multiprocessing import Process, Queue
from Params import configs

sys.path.insert(0, configs.dymola_path)
from dymola.dymola_interface import DymolaInterface


def simulate_model(model_name, stop_time, method, tmp_dir, queue):
    dymola = DymolaInterface()
    dymola.ExecuteCommand("Advanced.ParallelSimulations=1;")
    dymola.ExecuteCommand("Advanced.NumberOfCores=1;")
    dymola.openModel(path=os.path.join(configs.modelica_library_path, 'package.mo'))
    dymola.cd(tmp_dir)
    result = dymola.simulateModel(model_name, stopTime=stop_time, method=method, resultFile=tmp_dir)
    dymola.close()
    queue.put(result)


def main():
    # 读取模型列表
    with open('models.txt', 'r') as file:
        model_names = file.read().splitlines()

    # 确保结果目录存在
    if not os.path.exists(configs.dymola_res_dir):
        os.makedirs(configs.dymola_res_dir)

    # 为每个模型进行仿真测试
    for model_name in model_names:
        for stop_time in configs.stop_time_list:
            # 为每个仿真创建一个独立的临时目录
            tmp_dir = os.path.join(configs.dymola_tmp_dir, f"{model_name}_{stop_time}")
            if not os.path.exists(tmp_dir):
                os.makedirs(tmp_dir)

            queue = Queue()
            p = Process(target=simulate_model, args=(model_name, stop_time, configs.method, tmp_dir, queue))
            p.start()
            p.join(timeout=configs.timeout)

            try:
                if p.is_alive():
                    p.terminate()
                    p.join()
                    # 清理临时目录
                    shutil.rmtree(tmp_dir)
                    print(f"Timeout: Simulation for model {model_name} with stop time {stop_time} was terminated.")
                else:
                    result = queue.get()
                    if result:
                        print(f"Simulation successful for model {model_name} with stop time {stop_time}")
                        # 处理日志文件
                        dslog_src = os.path.join(tmp_dir, "dslog.txt")
                        dslog_dest = os.path.join(configs.dymola_res_dir,
                                                  f"{model_name}_{int(stop_time)}.txt")
                        if os.path.exists(dslog_src):
                            shutil.move(dslog_src, dslog_dest)
                        # 清理临时目录
                        shutil.rmtree(tmp_dir)
                        break
                    else:
                        # 清理临时目录
                        shutil.rmtree(tmp_dir)
                        print(f"Simulation failed for model {model_name} with stop time {stop_time}")
                        if stop_time == configs.stop_time_list[-1]:
                            print(f"All stop times attempted, simulation failed for model {model_name}")
            except Exception as e:
                print(f"Error: {e}")


if __name__ == '__main__':
    main()
